import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class DownLoadNode extends Thread{
    private List<String> list ;
    private  int start;
    private  int end;
    public HashMap keyFileMap ;
    private  String preUrlPath ;
    private  String fileRootPath ;

    public  DownLoadNode(List list, int start, int end, HashMap keyFileMap, String preUrlPath, String fileRootPath){
        this.list = list;
        
        this.end = end;
        this.start = start;
        this.keyFileMap = keyFileMap;
        this.preUrlPath = preUrlPath;
        this.fileRootPath = fileRootPath;
    }
    @Override
    public void run(){
            try{
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                for( int i = start;i<=end;i++){
                    int retryCount = 3;//下载失败 重试 3次
                    boolean downFlag = false;//是否已下载成功
                    while(retryCount>0&&!downFlag){
                        retryCount --;
                        String urlpath = list.get(i);
                        if(!urlpath.startsWith("http")){
                            urlpath = preUrlPath+urlpath;
                        }
                        URL url = new URL(urlpath);
                        //下在资源
                        DataInputStream dataInputStream = new DataInputStream(url.openStream());
                        String fileOutPath = fileRootPath+File.separator+i;
                        FileOutputStream fileOutputStream = new FileOutputStream(new File(fileOutPath));
                        byte[] bytes = new byte[1024];
                        int length = 0;
                        while ((length = dataInputStream.read(bytes)) != -1) {
                            fileOutputStream.write(bytes, 0, length);
                        }
                        dataInputStream.close();
                        fileOutputStream.flush();
                        fileOutputStream.close();
                        keyFileMap.put(i,fileOutPath);
                        downFlag =true;
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

    }
}
